local oo = require("SharedLibs.BaseLib")
local co = require("SharedLibs.CoroLib")

Debugger = require("SharedLibs.Debugger")
TimerMgr = require("SharedLibs.TimerMgr")
AsyncOp = require("SharedLibs.AsyncOp")
AsyncOpState = require("SharedLibs.AsyncOpState")

--[[
	可缩放的等待
]]
co.SWaitTime = oo.Class();
local SWaitTime = co.SWaitTime;
SWaitTime.name = "SWaitTime";
oo.ClassExtends(SWaitTime, AsyncOp);

--- seconds == 0 代表无等待（会同步执行到后续代码）
function co.SDelay(seconds, scale)
	assert(seconds >= 0);
	local op = oo.New(SWaitTime, seconds, scale);
	return co.yield(op);
end

--- 0代表无等待（会同步执行到后续代码）
function co.NewSDelay(seconds, scale)
	assert(seconds >= 0);
	return oo.New(SWaitTime, seconds, scale);
end

----
function SWaitTime.prototype:constructor(seconds, scale)
	SWaitTime._ss.prototype.constructor(self)

	--- 可以实时的修改这个Scale来实现加速/减速的效果
	self.scale = scale or 1;

	self._state = AsyncOpState.Ready
	self._interval = seconds;
	
	self._elapsedTime = 0;
	
	--- Implements ITickable
	self.isInQueue = false;
	self.isStopped = false;
end

function SWaitTime.prototype:_onStart()
	if self._interval == 0 then
		self:_doStop(true);
	else
		--- Cannot use TimerMgr.SetTimer, because it doesn't support pause/resume. 
		TimerMgr.Enqueue(self);

		self._elapsedTime = 0;
	end	
end

function SWaitTime.prototype:Update()
	if self._state ~= AsyncOpState.Executing then return end;

	local newElapsedTime = self._elapsedTime + TimerMgr.deltaTime * self.scale;
	self._elapsedTime = newElapsedTime;

	if newElapsedTime >= self._interval then
		self:_doStop(true);
	end;
end

function SWaitTime.prototype:_onStop()
	self.isStopped = true;
end

function SWaitTime.prototype:_onReset()
	self.isStopped = false;
end

function SWaitTime.prototype:Stop()
	if (AsyncOpState.Ready == self._state) or (AsyncOpState.Stopped == self._state) then
		return
	end

	self._state = AsyncOpState.Stopped
	self._continuation = nil	

	self._elapsedTime = 0;

	self.isStopped = true;
end

function SWaitTime.prototype:GetReturn()
	return self._interval;
end

return SWaitTime;
